﻿using System;
using System.Collections.Generic;
using System.Text;

using Newtonsoft.Json;

namespace System
{

    public class ObjectJsonConverter<T> : JsonConverter
    {

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            T obj = serializer.Deserialize<T>(reader);
            if (obj == null)
            {
                return null;
            }
            return JsonConvert.SerializeObject(obj);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                serializer.Serialize(writer, JsonConvert.DeserializeObject<T>(value.ToString()));
            }
            catch
            {
                writer.WriteNull();
            }
        }


        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }
}
